package Controller

import (
	"github.com/gin-gonic/gin"
	"github.com/jinzhu/copier"
	"log"
	"math"
	"net/http"
	"strconv"
	"time"
	"web_back_go/Common"
	"web_back_go/DAO"
	"web_back_go/DAO/gorm"
	"web_back_go/DAO/gorm/GormModel"
	models "web_back_go/DAO/model"
	"web_back_go/Dto"
	"web_back_go/Response"
)

/* noticeReS
 */
type noticeReS struct {
	ID          int64     `json:"id"`
	ShopId      int64     `json:"shopId"`
	Title       string    `json:"title"`
	Content     string    `json:"content"`
	PublishTime time.Time `json:"publishTime"`
}

/*
GetShopNoticePage
@Description: 获取通知列表
@param c
@return
*/
func GetShopNoticePage(c *gin.Context) {
	var engine = DAO.Engine
	var notices []models.TzNotice
	var notice models.TzNotice

	currentStr := c.Query("current")
	sizeStr := c.Query("size")
	status := c.Query("status")
	isTop := c.Query("isTop")
	title := c.Query("title")
	page, err := strconv.Atoi(currentStr)

	var count int64
	if err != nil || page < 1 {
		page = 1
	}

	size, err := strconv.Atoi(sizeStr)
	if err != nil || size < 1 {
		size = 10
	}

	conds := make([]string, 0, 3) // 直接使用 string 类型的切片
	params := make([]interface{}, 0, 3)
	query := "1=1"

	if status != "" {
		conds = append(conds, "status=?")
		params = append(params, status)

		query += " AND " + conds[len(conds)-1]
	}

	if isTop != "" {
		conds = append(conds, "is_top=?")
		params = append(params, isTop)
		query += " AND " + conds[len(conds)-1] // 这里不需要再次检查 query 是否为 "1=1"，因为已经添加了至少一个条件
	}

	if title != "" {
		conds = append(conds, "title like ?")
		params = append(params, "%"+title+"%")
		query += " AND " + conds[len(conds)-1]
	}

	// 执行查询
	err = engine.Where(query, params...).Limit(size, (page-1)*size).Find(&notices)
	if err != nil {
		// 处理查询错误
		c.JSON(http.StatusInternalServerError, gin.H{"error": err.Error()})
		return
	}

	// 计算总数
	count, err = engine.Where(query, params...).Count(&notice)
	if err != nil {
		// 处理计数错误
		c.JSON(http.StatusInternalServerError, gin.H{"error": err.Error()})
		return
	}
	// 如果没有结果，将 notices 设置为空切片，而不是 nil
	if len(notices) == 0 {
		notices = []models.TzNotice{}
	}

	// 构造响应
	c.JSON(http.StatusOK, Response.ResponseBody{
		Code: "00000",
		Data: Common.PageParam1[models.TzNotice]{
			Current: page,
			Total:   count,
			Size:    size,
			Records: notices,
			Pages:   int(math.Ceil(float64(count) / float64(size))),
		},
		Msg:       nil,
		Success:   true,
		Fail:      false,
		Version:   "1.0",
		Timestamp: time.Now().Unix(),
		Sign:      "",
	})
}

/*
GetTopNoticeList
@Description: 获取置顶通知列表
@param c
@return
*/
func GetTopNoticeList(c *gin.Context) {
	var db = gorm.Db
	var noticeList []GormModel.TzNotice

	// 添加查询条件和排序
	result := db.Table("tz_notice").
		Where("status = ? AND is_top = ?", 1, 1).
		Order("publish_time DESC").
		Find(&noticeList)

	if result.Error != nil {
		log.Println(result.Error)
		c.JSON(500, gin.H{
			"code":    "A00001",
			"msg":     "服务器异常",
			"data":    nil,
			"version": "1.0.0",
		})
		return
	}

	var noticeListRes []noticeReS
	// 使用 copier.Copy 将 GormModel.TzNotice 数据复制到 noticeReS
	err := copier.Copy(&noticeListRes, &noticeList)
	if err != nil {
		log.Println(err)
		c.JSON(500, gin.H{
			"code":    "A00001",
			"msg":     "服务器异常",
			"data":    nil,
			"version": "1.0.0",
		})
		return
	}

	c.JSON(200, gin.H{
		"code":    "00000",
		"msg":     "请求成功",
		"data":    noticeListRes,
		"version": "1.0.0",
	})
}

func GetNoticeById(c *gin.Context) {
	idStr := c.Param("id")
	id, err := strconv.ParseInt(idStr, 10, 64)
	log.Println(id)
	var notice GormModel.TzNotice
	db := gorm.Db
	if err := db.Where("id = ?", id).First(&notice).Error; err != nil {
		c.JSON(http.StatusOK, Response.ResponseBody{
			Code:    "A00001",
			Msg:     "参数错误",
			Data:    nil,
			Version: "1.0.0",
		})
		return
	}
	var noticeDto Dto.NoticeDto
	err = copier.Copy(&noticeDto, &notice)
	if err != nil {
		log.Println(err)
		c.JSON(200, Response.ResponseBody{
			Code:    "A00001",
			Msg:     "服务器异常",
			Data:    nil,
			Version: "1.0.0",
			Fail:    true,
			Success: false,
		})
		return
	}
	c.JSON(http.StatusOK, Response.ResponseBody{
		Code:    "00000",
		Msg:     "请求成功",
		Data:    noticeDto,
		Version: "1.0.0",
		Success: true,
		Fail:    false,
	})
}
